package grouplife::Controller::TaobaoLogin;
use Moose;
use namespace::autoclean;
use Catalyst qw/
Session
Session::Store::FastMmap
Session::State::Cookie
/;
use Util::Taobao::Authenticate;
use grouplife::Model::Store::StoreSearchModel;


BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Login - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut


sub index :Path :Args(0) {
	my ($self, $c) = @_;

# Get the username and password from form
	my $code= $c->request->params->{code};
	my $redirect_uri = $c->config->{redirect_uri}; 
	my $app_key = $c->config->{app_key};
	my $secret_key = $c->config->{secret_key};
	my $gateway_url = $c->config->{gateway_url};
	my $oauth_url = $c->config->{oauth_url};
	my $version = $c->config->{version};

	my $authenticator = Util::Taobao::Authenticate->new();
	my $user = $authenticator->get_userinfo($c, $code, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version);

	if($user->{code} == 0) {
		my @users = $c->model('Users::UsersSearchModel')->get_user_by_email($user->{email}); 

		my @bind_users;
		foreach my $u (@users) {
			if($u->active eq 'N') {
				$u->delete;
			}
			if($u->active eq 'Y') {
				push(@bind_users, $u);
			}
		}
		my $length = scalar(@bind_users);
		if ($length == 0) {
			#Returned stores whose picked = 'R' or 'Y'
			my @stores = $c->model('Store::StoreSearchModel')->get_unpicked_by_nick($user->{nick});
			foreach my $store (@stores) {
				 $store->update({owner_email => $user->{email}, picked => 'Y'});	
			}
			$c->stash(nick  =>  $user->{nick}),
			$c->stash(email =>  $user->{email}),
			$c->stash(css => 'zhuce.css'),
			$c->stash(javascript => '/user/form_create.js');
			$c->stash(template => 'taobao/taobao_oauth.tt2');
		} else {
			if( ($bind_users[0]->active eq 'Y') and ($user->{nick} eq $bind_users[0]->source_nick) and ($bind_users[0]->source eq '1')) {
				my $auth_user = $c->find_user({ id => $bind_users[0]->id });
				$c->authenticate({ email_address => $user->email_address, active => 'Y', password => $user->password  } );
				$c->session->{login_user} = $bind_users[0];
				$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$bind_users[0]->id]));
			} else {
				$c->stash(nick  =>  $user->{nick}),
				$c->stash(email =>  $user->{email}),
				$c->stash(user =>  $bind_users[0]),
				$c->stash(css => 'zhuce.css'),
				$c->stash(template => 'taobao_bind.tt2');
			}
		}

	}
}
=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
